<template>
  <!--弹出窗-->
  <modal ref="modal_1"
         :title="title"
         :isCloseConfirm="this.editable"
         :fullscreen="this.fullscreen"
         top="3%"
         width="80%"
         :close-on-click-modal="true"
         @modalOpened="opened"
         @modalClose="closed">

    <avue-form :option="option" ref="form" v-model="form" @submit="onSubmit" >
      <!--<template #serviceName v-if="this.editable">-->
        <!--<el-input v-model="form.serviceName" readonly placeholder="请选择业务人员" @click="selectServiceName" :disabled="!!this.form.id"/>-->
      <!--</template>-->
      <template #fclItem>
        <fcl-item ref="fclItem" @disabledCommit="disabledCommit" @disabledFiled="disabledFiled"></fcl-item>
      </template>
    </avue-form>
    <!--底部按钮块, 默认只有"取消"按钮-->
    <template #footerButton>
      <el-button type="primary" v-if="(permission.fcl_main_add || permission.fcl_main_edit) && editable"
                 :disabled="btnLoading" @click="this.$refs.form.submit()">保存
      </el-button>
      <el-button @click="$refs.modal_1.handleClose()">关闭</el-button>
    </template>
  </modal>
</template>

<script>
    import { getList, getDetail, add, update, remove } from "@/api/anwise/logistics/fcl_main";
    import {remoteList} from '@/api/anwise/customer/customer';
    import { mapGetters } from "vuex";
    import { getDeptTree } from '@/api/system/dept';
    import website from '@/config/website';
    import {Pattern} from "@/utils/validate.js";
    import {dateFormat} from "@/utils/date.js";

    import selectCustomer from '../../order/components/select_customer.vue';
    // import selectService from './select_service.vue';
    // import selectFactory from './select_factory.vue';
    import selectBank from '../../order/components/select_bank.vue';
    import fclItem from './fcl_item.vue';

    export default {
        components: {
            selectCustomer,
        //     selectService,
        //     selectFactory,
            selectBank,
            fclItem,
        },
        data() {
            return {
                isEnglish:'1',
                hiddenPrice:'1',
                hasItem:false,
                box:false,
                emits: ["success"],
                editable: false,
                title: "订单信息",
                isCloseConfirm: false,
                fullscreen: false,
                btnLoading: false,
                form: {},
                query: {},
                loading: true,
                option: {
                    card: true,
                    tabs: true,
                    tabsActive: 1,
                    height: 'auto',
                    calcHeight: 30,
                    labelWidth: 150,
                    menuWidth: 120,
                    submitBtn: false,
                    emptyBtn: false,
                    column: [
                        {
                            label: "FCL编号",
                            prop: "fclNo",
                            type: "input",
                            disabled:true,
                            display:true,
                            span:8,
                            placeholder:'保存后自动生成编号',
                            rules: [{
                                required: false,
                                message: "请输入FCL编号",
                                trigger: "blur"
                            }],
                        },
                        {
                            label: "柜号",
                            prop: "containerNo",
                            type: "input",
                            span:8,
                            rules: [{
                                required: false,
                                message: "请输入柜号",
                                trigger: "blur"
                            }],
                        },
                        {
                            label: "装柜地址",
                            prop: "loadingAddr",
                          type:"input",
                            // type: "select",
                            // sortable: true,
                            // filterable:true,
                            // dicUrl: '/api/blade-anwise/stock_home/selectAnwise',
                            // props: {
                            //     label: 'stockName',
                            //     value: 'stockName',
                            // },
                            // dataType: 'string',
                            span:8,
                        },
                        {
                            label: "出货日期",
                            prop: "deliveryDate",
                            type: "date",
                            valueFormat: 'YYYY-MM-DD',
                            format:'YYYY-MM-DD',
                            span:8,
                            rules: [{
                                required: true,
                                message: "请输入出货日期",
                                trigger: "blur"
                            }],
                        },
                        {
                            label: "司机资料",
                            prop: "driverInfo",
                            type: "input",
                            span:8,
                        },
                        {
                            label: "柜子皮重",
                            prop: "tareWeight",
                            type: "number",
                            precision:2,
                            min:0,
                            max:999999999,
                            controls:false,
                            span:8,
                        },
                        {
                            label: "截数日期",
                            prop: "cutoffDate",
                            type: "date",
                            valueFormat: 'YYYY-MM-DD',
                            format:'YYYY-MM-DD',
                            span:8,
                        },
                        {
                            label: "封条号",
                            prop: "sealNo",
                            type: "input",
                            span:8,
                        },
                        {
                            label: "货代",
                            prop: "forwarder",
                            type: "input",
                            span:8,
                        },
                        {
                            label: "S/O",
                            prop: "soInfo",
                            type: "input",
                            span:8,
                        },
                        {
                            label: "SI & VGM CUT",
                            prop: "siCut",
                            type: "input",
                            span:8,
                        },
                        {
                            label: "Vessel/Voy",
                            prop: "vesselVoy",
                            type: "input",
                            span:8,
                        },
                        {
                            label: "ETD",
                            prop: "etd",
                            type: "date",
                            valueFormat: 'YYYY-MM-DD',
                            format:'YYYY-MM-DD',
                            span:8,
                        },
                        {
                            label: "ETA",
                            prop: "eta",
                            type: "date",
                            valueFormat: 'YYYY-MM-DD',
                            format:'YYYY-MM-DD',
                            span:8,
                        },
                        {
                            label: "运输公司",
                            prop: "transitCompany",
                            type: "input",
                            span:8,
                        },
                        {
                          label: "起运港",
                          prop: "loadingPort",
                          type: "input",
                          span:8,
                        },
                        {
                          label: "卸货港",
                          prop: "dischargePort",
                          type: "input",
                          span:8,
                        },
                        {
                          label: "柜型",
                          prop: "containerType",
                          type: "select",
                          filterable: true,
                          dicUrl: "/blade-system/dict-biz/dictionary?code=Container model",
                          props: {
                            label: 'dictValue',
                            value: 'dictKey',
                          },
                          allowCreate:true,
                          dataType: 'string',
                          span:8,
                        },
                        {
                            label: "箱唛",
                            prop: "packLabel",
                            type: "textarea",
                            span:24,
                            minRows:2,
                            maxRows:5,
                        },

                    ],
                    group: [
                        {
                            icon: 'el-icon-house',
                            label: 'FCL项信息',
                            prop: 'group1',
                            column: [
                                {
                                    label: '',
                                    prop: 'fclItem',
                                    className: 'addPadding',
                                    span: 24,
                                    labelWidth: 0,
                                    formslot: true,
                                    display: true,
                                },
                            ],
                        },
                    ]
                },
                data: []
            };
        },
        computed: {
            ...mapGetters(["permission"]),
            permissionList() {
                return {
                    addBtn: this.validData(this.permission.fcl_main_add, false),
                    viewBtn: this.validData(this.permission.fcl_main_view, false),
                    delBtn: this.validData(this.permission.fcl_main_delete, false),
                    editBtn: this.validData(this.permission.fcl_main_edit, false)
                };
            },
            ids() {
                let ids = [];
                this.selectionList.forEach(ele => {
                    ids.push(ele.id);
                });
                return ids.join(",");
            }
        },
        mounted() {
        },
        methods: {
            disabledFiled(hasItem) {
                this.hasItem = hasItem;
            },
            changeDeliDate(value) {
                let fclItem = this.$refs.fclItem.$refs.tableRef.getTableData().fullData;
                if (fclItem.length > 0) {
                    fclItem.forEach(item => {
                        item.deliDate = value;
                    })
                }
            },
            disabledCommit(data) {
                this.btnLoading = data;
            },
            async validItemEvent() {
                const $table = this.$refs.fclItem.$refs.tableRef
                let errMap = undefined;
                    await $table.validate().then((err) => {
                        console.log("err:",err)
                        errMap=err;
                    })
                  return errMap;
            },
            async onSubmit(form, done) {
                const $table = this.$refs.fclItem.$refs.tableRef
                let checkfclItem = false;
                 const errMap = await this.validItemEvent();
                  console.log(errMap);
                     if (errMap) {
                         this.$message({
                             type: 'error',
                             message: 'FCL项信息有误！',
                         });
                         checkfclItem = true;
                         done();
                         return;
                     }

                console.log("checkfclItem",checkfclItem);
                if (!checkfclItem) {
                    this.btnLoading = true;
                    form.addList = $table.getInsertRecords();
                    form.updateList = $table.getUpdateRecords();
                    form.deleteList = $table.getRemoveRecords();
                    form.itemList = $table.getTableData().fullData;
                    if (!form.itemList || form.itemList.length < 1) {
                        this.$message({
                            type: 'error',
                            message: '无FCL项信息！',
                        });
                        done();
                        this.btnLoading = false;
                        return;
                    }
                    console.log(form)
                    update(form).then(res => {
                        if (res.data.success) {
                            this.$message({
                                type: "success",
                                message: res.msg || "保存成功!"
                            });
                            setTimeout(() => {
                              this.btnLoading = false;
                              done();
                                this.$refs.modal_1.hide();
                            }, 1000)
                        } else {
                            this.$message({
                                type: "error",
                                message: res.msg || "保存失败!"
                            });
                        }
                    }).catch(err => {
                        console.log(err)
                        done();
                        this.btnLoading = false;
                    })

                }
            },
            show(option) {
                this.title = option.title;
                this.type = option.type;
                this.option.detail = this.type === "view";
                this.editable = this.type !== "view";
                this.customer = {};
                if (option.id) {
                    this.hasItem=true;
                    console.log("option.id");
                    setTimeout(() => {
                        getDetail(option.id).then(res => {
                            if (res.data.success) {
                                this.form = res.data.data;
                                // this.customer.salesName =  this.form.customer.cartonMarkRemark;
                                // this.customer.remark = this.form.customer.prodRemark;
                                // this.customer.salesRemark = this.form.customer.salesRemark;
                                this.$refs.fclItem.setData(this.editable, this.form.fclNo)
                                this.$refs.fclItem.asnList=this.form.asnList;
                                // this.$refs.fclItem.idNo=this.form.idNo;
                                // this.$refs.fclItem.bankId= this.form.bankId;
                                // this.$refs.fclItem.editable = this.editable;
                                // this.$refs.fclItem.salesDate = this.salesDate;
                                // this.form.taxRate = Number(this.form.taxRate)
                                // this.findObject(this.option.column, 'idNo').display = true;
                                // this.findObject(this.option.column, 'version').display = true;

                                // const column =  this.findObject(this.option.column, 'contact');
                                // column.dicData=[];
                                // if (res.data.data.customer.contact1) {
                                //     column.dicData.push({name:res.data.data.customer.contact1});
                                // }
                                // if (res.data.data.customer.contact2) {
                                //     column.dicData.push({name:res.data.data.customer.contact2});
                                // }
                                // if (res.data.data.customer.contact3) {
                                //     column.dicData.push({name:res.data.data.customer.contact3});
                                // }
                                // console.log("column",column);
                            }
                        })
                    }, 500);
                } else {
                    this.form = {}
                    // this.form.asnDate = dateFormat(new Date(),"yyyy-MM-dd")
                    this.hasItem=false;

                }

                this.$refs.modal_1.show();
            },
            rowDel(row) {
                this.$confirm("确定将选择数据删除?", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                })
                    .then(() => {
                        return remove(row.id);
                    })
                    .then(() => {
                        this.$message({
                            type: "success",
                            message: "操作成功!"
                        });
                    });
            },
            handleDelete() {
                if (this.selectionList.length === 0) {
                    this.$message.warning("请选择至少一条数据");
                    return;
                }
                this.$confirm("确定将选择数据删除?", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                })
                    .then(() => {
                        return remove(this.ids);
                    })
                    .then(() => {
                        this.$message({
                            type: "success",
                            message: "操作成功!"
                        });
                        this.$refs.crud.toggleSelection();
                    });
            },
            beforeOpen(done, type) {
                if (["edit", "view"].includes(type)) {
                    getDetail(this.form.id).then(res => {
                        this.form = res.data.data;
                    });
                }
                done();
            },
            opened() {
                console.log("opened")
            },
            closed() {

                this.$emit("success");
            }
        }
    };
</script>

<style>
  /*.addPadding {*/
    /*padding: 20px !important;*/
  /*}*/
</style>
